package com.pacific.sign.common.utils;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 图片工具类
 */
public class ImageUtil {

    private static int interval = 100;

    /**
     * 上传图片(base64)
     */
    public static String uploadImg(String imgData){

        String imgUrl = "";
        //临时路径
        String tempFileDir = "D://";
        File FileDir = new File(tempFileDir);
        if(!FileDir.exists()){
            FileDir.mkdirs();
        }
        tempFileDir = tempFileDir + "test.jpg";

        //转换为图片
        String2Img(imgData, tempFileDir, "jpg");

        // 上传到FTP
        File file = new File(tempFileDir);

//        imgUrl = uploadByFtp(file);
//        //删除临时文件
//        file.delete();

        imgUrl = tempFileDir;

        return imgUrl;
    }


    /**
     * 字符转图片文件
     * @Description：
     * @param imgData 图片字符串
     * @param filePath 转存文件路径
     * @param suffix: 图片格式
     * @return void:
     */
    public static void String2Img(String imgData, String filePath, String suffix){
        if(StringUtils.isBlank(imgData)){
            return;
        }
        imgData = imgData.replace("data:image/png;base64,", "").replace("data:image/jpeg;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decodeBuffer(imgData);
            org.apache.commons.codec.binary.Base64 base64 = new org.apache.commons.codec.binary.Base64();
            byte[] debytes = base64.decodeBase64(imgData.getBytes());
            byte[] k = base64.decode(imgData);
            ByteArrayInputStream bais = new ByteArrayInputStream(k);
            BufferedImage image = ImageIO.read(bais);
            if (image != null)
            {
                //保存图片到指定的目录和文件中
                ImageIO.write(image, suffix, new File(filePath));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 给图片添加水印图片、可设置水印图片旋转角度
     *
     * @param waterImgPath
     *            水印图片路径
     * @param srcImgPath
     *            源图片路径
     * @param targerPath
     *            目标图片路径
     * @param degree
     *            水印图片旋转角度
     *  @Param alpha 水印透明度  0.1-1
     */
    public static void waterMarkByImg(String waterImgPath, String srcImgPath,
                                      String targerPath, double degree,float alpha) {
        OutputStream os = null;
        try {

            Image srcImg = ImageIO.read(new File(srcImgPath));

            BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                    srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);

            // 1、得到画笔对象
            Graphics2D g = buffImg.createGraphics();

            // 2、设置对线段的锯齿状边缘处理
            g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg
                    .getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
            // 3、设置水印旋转
            if (0 != degree) {
                g.rotate(Math.toRadians(degree),
                        (double) buffImg.getWidth() / 2, (double) buffImg
                                .getHeight() / 2);
            }

            // 4、水印图片的路径 水印图片一般为gif或者png的，这样可设置透明度
            ImageIcon imgIcon = new ImageIcon(waterImgPath);

            // 5、得到Image对象。
            Image img = imgIcon.getImage();

            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
                    alpha));

            // 6、水印图片的位置
            for (int height = interval + imgIcon.getIconHeight(); height < buffImg.getHeight()*100; height = height +interval+ imgIcon.getIconHeight()) {
                for (int weight = interval + imgIcon.getIconWidth(); weight < buffImg.getWidth()*100; weight = weight +interval+ imgIcon.getIconWidth()) {
                    g.drawImage(img, weight - imgIcon.getIconWidth() - 1000, height
                            - imgIcon.getIconHeight() - 1000, null);
                }
            }
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            // 7、释放资源
            g.dispose();

            // 8、生成图片
            os = new FileOutputStream(targerPath);
            ImageIO.write(buffImg, "JPG", os);

            System.out.println("图片完成添加水印图片");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os)
                    os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 对图片进行放大
     * @param originalImage 原始图片
     * @param times 放大倍数
     * @return
     */
    public static BufferedImage  zoomInImage(BufferedImage  originalImage, Integer times){
        int width = originalImage.getWidth()*times;
        int height = originalImage.getHeight()*times;
        BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0,0,width,height,null);
        g.dispose();
        return newImage;
    }
    /**
     * 对图片进行放大
     * @param srcPath 原始图片路径(绝对路径)
     * @param newPath 放大后图片路径（绝对路径）
     * @param times 放大倍数
     * @return 是否放大成功
     */
    public static boolean zoomInImage(String srcPath,String newPath,Integer times){
        BufferedImage bufferedImage = null;
        try {
            File of = new File(srcPath);
            if(of.canRead()){
                bufferedImage =  ImageIO.read(of);
            }
        } catch (IOException e) {
            //TODO: 打印日志
            return false;
        }
        if(bufferedImage != null){
            bufferedImage = zoomInImage(bufferedImage,times);
            try {
                //TODO: 这个保存路径需要配置下子好一点
                ImageIO.write(bufferedImage, "JPG", new File(newPath)); //保存修改后的图像,全部保存为JPG格式
            } catch (IOException e) {
                // TODO 打印错误信息
                return false;
            }
        }
        return true;
    }


    /**
     * 对图片进行缩小
     * @param originalImage 原始图片
     * @param times 缩小倍数
     * @return 缩小后的Image
     */
    public static BufferedImage  zoomOutImage(BufferedImage  originalImage, Integer times){
        int width = originalImage.getWidth()/times;
        int height = originalImage.getHeight()/times;
        BufferedImage newImage = new BufferedImage(width,height,originalImage.getType());
        Graphics g = newImage.getGraphics();
        g.drawImage(originalImage, 0,0,width,height,null);
        g.dispose();
        return newImage;
    }
    /**
     * 对图片进行缩小
     * @param srcPath 源图片路径（绝对路径）
     * @param newPath 新图片路径（绝对路径）
     * @param times 缩小倍数
     * @return 保存是否成功
     */
    public static boolean zoomOutImage(String srcPath,String newPath,Integer times){
        BufferedImage bufferedImage = null;
        try {
            File of = new File(srcPath);
            if(of.canRead()){
                bufferedImage =  ImageIO.read(of);
            }
        } catch (IOException e) {
            //TODO: 打印日志
            return false;
        }
        if(bufferedImage != null){
            bufferedImage = zoomOutImage(bufferedImage,times);
            try {
                //TODO: 这个保存路径需要配置下子好一点
                ImageIO.write(bufferedImage, "JPG", new File(newPath)); //保存修改后的图像,全部保存为JPG格式
            } catch (IOException e) {
                // TODO 打印错误信息
                return false;
            }
        }
        return true;
    }




    public static void main(String[] args) {


        //添加旋转满屏水印图片
        waterMarkByImg("D://tt.jpg", "D://java.jpg", "D://java3.jpg",30,(float)0.1);

        //图片放大
        //zoomInImage("D://t.jpg","D://t2.jpg",3);

        //图片缩小
        //zoomOutImage("D://t.jpg","D://t3.jpg",3);




    }

}
